package main

import (
	"LterServer/model"
	_ "LterServer/routers"
	"encoding/json"
	"LterServer/util"
	"time"

	"gitee.com/konyshe/gogo"
)

func wsHandle(data []byte, conn *gogo.ImplConnection) ([]byte, error) {
	var recvJsonMap map[string]interface{}
	err := json.Unmarshal(data, &recvJsonMap)
	if err != nil {
		return nil, err
	}

	var (
		RecvAction string
		UserName   string
		Passwd     string
	)

	value, ok := recvJsonMap["action"]
	if ok {
		RecvAction = value.(string)
	} else {
		return nil, nil
	}

	d := make(map[string]interface{})
	d["action"] = RecvAction

	if RecvAction == "app_version" {
		versionMap, err := model.GetVersionMap()
		if err == nil {
			d["app_version"] = versionMap["app_version"]["value"].(string)
			d["apk_url"] = versionMap["apk_url"]["value"].(string)
			d["tip"] = versionMap["tip"]["value"].(string)

			return json.Marshal(d)
		}
	}

	value, ok = recvJsonMap["username"]
	if ok {
		UserName = value.(string)
	} else {
		return nil, nil
	}

	value, ok = recvJsonMap["passwd"]
	if ok {
		Passwd = value.(string)
	} else {
		return nil, nil
	}

	userInfo, loginErr := model.LoginUser(UserName, Passwd)
	if RecvAction == "login" {
		if loginErr == nil {
			d["state"] = 1
			d["data"] = userInfo

		} else {
			d["state"] = 0
			d["data"] = loginErr.Error()
		}

		jsonRet, err := json.Marshal(d)
		if err == nil {
			gogo.LogInfo("Login " + UserName + " " + string(jsonRet[:]))
			return jsonRet, nil
		}

		return nil, nil

	} else if loginErr != nil {
		gogo.LogError(loginErr)
		return nil, nil
	}

	switch RecvAction {
	case "lter_start":
		{
			conn.SetGroup("lter")
			d["state"] = 1

			return json.Marshal(d)
		}

	case "lter_stop":
		{
			conn.OutGroup()
			d["state"] = 1

			return json.Marshal(d)
		}

	case "phone":
		{
			d["data"] = model.GetLterPhoneInfoListJSON()
			return json.Marshal(d)
		}
	}

	return nil, nil
}

func GetLter() map[string]interface{} {
	d := make(map[string]interface{})
	d["action"] = "lter"
	d["net"] = util.HealthNet()
	d["memory"] = util.HealthMemory()
	d["cpu"] = util.HealthCPU()
	d["client"] = model.GetLterClientInfoListJSON()

	return d
}

func WetSocketForSend() {
	for {
		if SendJSONStr, err := json.Marshal(GetLter()); err == nil {
			gogo.WebSocketSendToGroup(SendJSONStr, "lter")
		}

		time.Sleep(1 * time.Second)
	}
}

func ControlWebStart(controlPort int) {
	dbHost := "localhost:3309"
	if M_DEBUG {
		dbHost = "10.1.19.209:3309"
	}

	dataSourceName := "lter:E97VpZeQ3gS3N9kncy5Bs2rfcps@tcp(" + dbHost + ")/lter?charset=utf8"

	if err := gogo.SQLInit("mysql", dataSourceName, 500, 3); err != nil {
		gogo.CheckError(err)
	}

	go gogo.StartWebSocket("/ws", controlPort, wsHandle)

	go WetSocketForSend()
}
